package com.viewpagerindicator.sample;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.viewpagerindicator.sample.adapters.DeviceListAdapter;
import com.viewpagerindicator.sample.adapters.DeviceScanListAdapter;

/**
 * Created by lizong on 2015/11/12.
 * 选择蓝牙设备
 */
public class DeviceActivity extends AppCompatActivity implements View.OnClickListener{
    private ListView listView;
    private DeviceScanListAdapter adapter;
    private View listviewBg; //列表试图
    private View progressingBg;//等待试图;
    private View errormsgBg;//错误试图;
    TextView title ;
    TextView desc;
    TextView progressTitle;

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;

    private static final int REQUEST_ENABLE_BT = 1;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    Button buttonSearch;

    CutokApplication application;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.devices_layout);
        buttonSearch= (Button) findViewById(R.id.btn_bluetooth_search);
        application= (CutokApplication) getApplication();
        listView= (ListView) findViewById(R.id.first_layout_listview);
        listviewBg=  findViewById(R.id.list_bg);
        progressingBg=  findViewById(R.id.progress_bg);
        errormsgBg=  findViewById(R.id.errormsg_bg);
        buttonSearch= (Button) findViewById(R.id.btn_bluetooth_search);
        //检查设备是否支持低功耗蓝牙
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            show(errormsgBg,getString(R.string.error_bluute_cantsupport),null);
            return;
        }
        //获取bluetoothAdapter
        final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        //检查设备是否支持
        if (mBluetoothAdapter == null) {
            show(errormsgBg, getString(R.string.error_bluute_cantsupport), null);
            return ;
        }

        adapter=new DeviceScanListAdapter(this,R.layout.device_scan_item,application.deviceList);
        listView.setAdapter(adapter);
        errormsgBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show(listviewBg);
                //开启蓝牙设备
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                // 设置蓝牙可见性，最多300秒
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(intent);
                scanLeDevice(true);
            }
        });
        title= (TextView) findViewById(R.id.errormsg_title);
        desc= (TextView) findViewById(R.id.errormsg_desc);
        progressTitle= (TextView) findViewById(R.id.progress_bg_title);

        show(progressingBg, getString(R.string.btn_bluetooth_search), null);
        progressingBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (application.deviceList.size() == 0) {
                    show(errormsgBg, getString(R.string.btn_bluetooth_search_no), null);
                } else {
                    show(listviewBg);
                }
            }
        });
        buttonSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show(progressingBg);
                scanLeDevice(true);
            }
        });
        if(mBluetoothAdapter.isEnabled()){
            if(application.deviceList.size()<=0){
                scanLeDevice(true);
                show(listviewBg);
            }
        }else{
            show(errormsgBg, getString(R.string.error_blute_close),getString(R.string.error_bluetooth_desc));
        }

    }
    public void show(View viewToShow){
        if(viewToShow.getId()==progressingBg.getId()){
            errormsgBg.setVisibility(View.GONE);
            progressingBg.setVisibility(View.VISIBLE);
        }else if(viewToShow.getId()==errormsgBg.getId()){
            progressingBg.setVisibility(View.GONE);
            errormsgBg.setVisibility(View.VISIBLE);
        }else if(viewToShow.getId()==listviewBg.getId()){
            errormsgBg.setVisibility(View.GONE);
            progressingBg.setVisibility(View.GONE);
        }
    }
    public void show(View viewToShow,String errorTitle,String errorDesc){
        if(viewToShow.getId()==progressingBg.getId()){
            errormsgBg.setVisibility(View.GONE);
            progressingBg.setVisibility(View.VISIBLE);
        }else if(viewToShow.getId()==errormsgBg.getId()){
            progressingBg.setVisibility(View.GONE);
            errormsgBg.setVisibility(View.VISIBLE);
        }

        if(viewToShow.getId()==errormsgBg.getId()){
            title.setText(errorTitle);
            desc.setText(errorDesc);
        }
        if(viewToShow.getId()==progressingBg.getId()){
            progressTitle.setText(errorTitle);
        }
    }
    /**
     * @param  enable  true:搜索，false：停止搜索
     * */
    private void scanLeDevice(final boolean enable) {
        if(mScanning){
            return;
        }
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mScanning)
                    {
                        mScanning = false;
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                        mHandler.sendEmptyMessage(2);
                    }
                }
            }, SCAN_PERIOD);

            mScanning = true;
            //F000E0FF-0451-4000-B000-000000000000
            application.deviceList.clear();
            mHandler.sendEmptyMessage(1);
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
    }
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            application.deviceList.add(device);
                            mHandler.sendEmptyMessage(1);
                        }
                    });
                }
            };
    // Hander
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: // Notify change
                    adapter.notifyDataSetChanged();
                    break;
                case 2: // Notify change
                    adapter.notifyDataSetChanged();
                    show(listviewBg);
                    break;
            }
        }
    };


    @Override
    public void onClick(View view) {
        //用户选择蓝牙设备点击按钮事件
        if(view.getTag()!=null){
            Intent intent=new Intent();
            intent.putExtra("address",(BluetoothDevice)view.getTag());
            setResult(GoodsDetailActivity.REQUESTID_OF_CHOICEBLUEDEVICE, intent);
            finish();
        }
    }
    //弹出开启蓝牙dialog
    public void showDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.error_blute_close));
        builder.setMessage(getString(R.string.is_open_bluetooth));
        builder.setNegativeButton(getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                finish();
            }
        });
        builder.setPositiveButton(getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                //开启蓝牙设备
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                // 设置蓝牙可见性，最多300秒
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(intent);
            }
        });
    }
    public void back(View view){
        finish();
    }
}
